package controllers

import (
	"app/models"
	beego "github.com/beego/beego/v2/server/web"
	"math"
)

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}
type JsonPage struct {
	Code    int         `json:"code"`
	Msg     string      `json:"msg"`
	Data    interface{} `json:"data"`
	Page    int         `json:"page"`
	Sumpage int         `json:"sumpage"`
	Size    int         `json:"size"`
	Count   int64       `json:"count"`
}
type AppController struct {
	beego.Controller
}

func (c *AppController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var alluser []models.App
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	sumpage := int(math.Ceil(float64(count) / float64(size)))
	offset := (page - 1) * size
	err := models.DB.Offset(offset).Limit(size).Find(&alluser).Error
	if err != nil {
		res := JsonR{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := JsonPage{
			Code:    200,
			Msg:     "查询成功",
			Data:    alluser,
			Page:    page,
			Sumpage: sumpage,
			Size:    size,
			Count:   count,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *AppController) Del() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.App{}, id).Error
	if err != nil {
		res := JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *AppController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	name := c.GetString("name")
	ly := c.GetString("ly")
	hy := c.GetString("hy")
	garde := c.GetString("garden")
	tel := c.GetString("tel")
	phone := c.GetString("phone")
	allapp := models.App{
		Name:  name,
		Ly:    ly,
		Hy:    hy,
		Garde: garde,
		Tel:   tel,
		Phone: phone,
	}
	err := models.DB.Create(&allapp).Error
	if err != nil {
		res := JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: allapp,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
